package com.ruoyi.api.sms;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.RandomUtil;
import com.ruoyi.redis.RedisService;
import com.ruoyi.result.ResultView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

@EnableAsync
@RestController
@RequestMapping("/api/sms")
@Slf4j
public class SmsController {
    @Autowired
    private ISMSService ismsService;

    @Value("${sms-accessKeyId}")
    private String accessKeyId;
    @Value("${sms-secret}")
    private String secret;
    //    @Value("${sms-signName}")
    private String signName = "深圳市环资源科创";

    //验证码
    @Value("${sms-templateCode_verification}")
    private String verificattemplateCode;
    @Autowired
    private RedisService redisService;

    @RequestMapping(value = "/sendPhoneMsg", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResultView sendPhoneMsg(@NotBlank @NotNull String phoneNumber, String bizType) {
        JSONObject o = null;
        StringBuilder sb = new StringBuilder();
        String smsCode = String.valueOf(RandomUtil.getRandom(9)) + (RandomUtil.getBetweenRandom(100, 999));
        sb.append("{\"code\":\"").append(smsCode).append("\"}");
        o = ismsService.smsSend(sb.toString(), phoneNumber, accessKeyId, secret, signName, verificattemplateCode);
        String msg = null;
        if (o != null) {//成功,返回smscode
            if ("OK".equalsIgnoreCase(o.getString("Code"))) {
                redisService.set(smsCode, phoneNumber, 3600);//1小时有效
                return ResultView.ok(smsCode);
            }
            msg = o.getString("Message");
        } else {
            msg = "网络出错,请稍后再试";
        }
        return ResultView.error(-1, msg);
    }
}
